<template>
  <el-card class="box-card">
    <itable
    :table="tconfig.tableConfig"
    :tableData="tconfig.tableData"
    :page-bean="tconfig.pageBean"
    @pageChange="pageChange"
    @handleInfo="handleInfo"
    @handleSubmit="handleSubmit"
    @handleEdit="handleEdit"
    @handleDel="handleDel"
    >
      <template #searchBox>
        <Eform
          :model="form"
          :elem="fromData"
          :submit="true"
          :reset="true"
          :button="false"
          okIcon="Search"
          btnSize="default"
          submitText="搜索"
          @onSuccess="onSuccess"
          @onReset="onReset"
          >
        </Eform>
      </template>
      <template #is_doorkeeper="prop">{{ prop.obj.row.is_doorkeeper?'是':'否' }}</template>
      <template #is_reception_bug="prop">{{ prop.obj.row.is_reception_bug?'是':'否' }}</template>
      <template #is_danger="prop">{{ prop.obj.row.is_danger?'是':'否' }}</template>
      <template #is_check_bug="prop">{{ prop.obj.row.is_check_bug?'是':'否' }}</template>
      <template #is_answer="prop">{{ prop.obj.row.is_answer?'是':'否' }}</template>
      <!-- <template #check_frequency="prop">{{ prop.obj.row.check_frequency?'是':'否' }}</template> -->
      <template #headerbtn>
        <div style="display: flex;">
          <el-button type="primary" plain @click="exportModelData">下载风险管控清单模板</el-button>
          <el-button type="primary" plain @click="exportData" icon="Upload">导出隐患排查清单</el-button>
          <upfile @upload-success="handleSuccess" btntext="导入风险管控清单" ref="fileRef"/>
          <el-button type="primary" plain @click="clickadd" icon="Plus">添加</el-button>
        </div>
      </template>
    </itable>

    <el-dialog
    :title="title == 0?'新增':title == 1 ? '编辑' : '安全清单'"
    v-model="dialogVisible"
    :before-close="beforeClose"
    width="40%">
      <template v-if="title!==3">
          <Eform
          :model="formModel"
          :elem="formConfig"
          :rules="rules"
          labelWidth="130px"
          :button="false"
          ref="ruleFormRef"
          :inline="false"
          :style="{width:'100%'}"
          >
        </Eform>
      </template>
      <template v-else>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="编辑清单" name="0">
            <el-form
              label-position="left"
              label-width="100px"
              :model="formLabelAlign"
              ref="ruleFormRef1"
            >
              <el-form-item label="安全检查频率" prop="check_frequency">
                <el-radio-group v-model="formLabelAlign.check_frequency" >
                  <el-radio-button v-for="(item, index) in option" :key="index" :label="item.value">{{ item.label }}</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="风险点类型" prop="bugs_type">
                <el-select v-model="formLabelAlign.bugs_type" class="m-2" placeholder="请选择风险点类型">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="风险点等级" prop="bugs_level">
                <el-select v-model="formLabelAlign.bugs_level" class="m-2" placeholder="请选择风险点等级">
                  <el-option
                    v-for="item in levelData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="责任人" prop="director">
                <el-input v-model="formLabelAlign.director" placeholder="请输入责任人"/>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="编辑项目" name="1">
            <itable
            :table="tconfig1.tableConfig"
            :tableData="tconfig1.tableData"
            :page-bean="tconfig1.pageBean"
            @pageChange="pageChange1"
            @handleEdit="handleEdit1"
            @handleDel="handleDel1"
            >
            <template #headerbtn>
              <el-button type="primary" plain @click="addProject" icon="Plus">添加检查项目</el-button>
            </template>
          </itable>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template #footer>
          <span class="dialog-footer" v-if="activeName !== '1'">
            <el-button @click="clickCancel">取 消</el-button>
            <el-button type="primary" @click="clickComfig">保 存</el-button>
          </span>
      </template>
  </el-dialog>
  <el-dialog
    v-model="dialogVisible2"
    title="编辑"
    draggable
    width="30%"
    :before-close="handleClose"
    >
    <el-form :model="dialogForm" ref="dialogFormRef" :rules="dialogRules">
      <el-form-item label="排序" prop="sort">
        <el-input-number :min="0" v-model="dialogForm.sort" clearable/>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="dialogForm.content" type="textarea" autosize clearable/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clickCancel2(dialogFormRef)">取消</el-button>
        <el-button type="primary" @click="clickConfirm2(dialogFormRef)">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogVisible3"
    title="所属员工"
    draggable
    width="30%">
    <span style="color: rgb(150, 150, 150);">注: 请慎重更换职位工作，新的职位工作将在明天开始生效。新职位生效前，此处还会显示之前的职位。</span>
    <div style="width:100%;display: flex;justify-content: flex-end;">
      <el-button type="primary" plain @click="addstaff">添加成员</el-button>
    </div>
    <itable
      :table="tconfig2.tableConfig"
      :tableData="tconfig2.tableData"
      :page-bean="tconfig2.pageBean"
      @pageChange="pageChange2"
      @handleDel="handleClickdel"
      ></itable>
  </el-dialog>
  <staffList :drawer="drawerFlag" :select_type="select_type" @drawerClose="drawerClose" @confirmClick="confirmClick"/>
  </el-card>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue';
import { PageBean } from "@/utils/page-bean";
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'
import itable from '@/components/table/table.vue'
import Eform from '@/components/eform/index.vue';
import { ElMessageBox } from 'element-plus'
import useCurrentInstance from '@/utils/useCurrentInstance'
import staffList from '../components/staffList.vue';
import upfile from '@/components/upfile.vue';

const { proxy } = useCurrentInstance()
const store = useStore()
const router = useRouter()
const fileRef = ref()
let dialogVisible = ref(false)
let dialogVisible2 = ref(false)
let dialogVisible3 = ref(false)
let confirmFlag = ref(true)
let drawerFlag = ref(false)
const activeName = ref('0')
const select_type = ref('2')
let ruleFormRef = ref()
let dialogFormRef = ref()
let ruleFormRef1 = ref()
let params = ref({
  id:''
})
let title = ref(0)
const positionInfo = ref()
let options = reactive([]) as any
let levelData = reactive([]) as any
let fromData = reactive([
  {
    label: "职位名称",
    prop: "name",
    clearable: true,
  }
])
let form = reactive({
  name:'',
  page:1,
  size:10
})
let option = [
  {value:1,label:'每天'},
  {value:2,label:'每周'},
  {value:3,label:'每月'},
  {value:4,label:'每季度'},
  {value:5,label:'每年'}
]
let formConfig = reactive([
  {
    label: "职位名称",
    prop: "name",
    style:{paddingBottom:'15px'},
    clearable: true,
  },
  {
    label: "外来访客核销",
    prop: "is_doorkeeper",
    element:'switch',
    activeValue:1,
    inactiveValue:0,
    clearable: true,
  },
  {element:'text',textType:'开启后，此职位员工可以给外来访客扫描离场',switchStyle:{margin:'5px 0',color:'#888'}},
  {
    label: "是否接收隐患",
    prop: "is_reception_bug",
    element:'switch',
    activeValue:1,
    inactiveValue:0,
    clearable: true,
  },
  {element:'text',textType:'开启后，此岗位人员有权接收隐患并分配整改',switchStyle:{margin:'5px 0',color:'#888'}},
  {
    label: "是否参与危险作业",
    prop: "is_danger",
    element:'switch',
    activeValue:1,
    inactiveValue:0,
    clearable: true,
  },
  {element:'text',textType:'开启后,此职位员工将可以进行危险作业,并记录',switchStyle:{margin:'5px 0',color:'#888'}},
  {
    label: "是否进行安全检查",
    prop: "is_check_bug",
    element:'switch',
    activeValue:1,
    inactiveValue:0,
    clearable: true,
  },
  {element:'text',textType:'开启后，此职位员工根据频率，推送安全检查清单',switchStyle:{margin:'5px 0',color:'#888'}},
  {
    label: "安全检查频率",
    option:option,
    prop: "check_frequency",
    style:{padding:'15px 0'},
    type:'button',
    element:'radio',
    clearable: true,
  },
  {
    label: "是否晨会答题",
    prop: "is_answer",
    element:'switch',
    activeValue:1,
    inactiveValue:0,
    clearable: true,
  },
  {element:'text',textType:'开启后,此职位员工完成晨会后,将参与答题',switchStyle:{margin:'5px 0',color:'#888'}},
])
let formModel = reactive({
  name:'',
  id:'',
  is_doorkeeper:1,
  is_reception_bug:1,
  is_danger:1,
  is_check_bug:1,
  check_frequency:1,
  is_answer:1,
})
const dialogForm = reactive({
  id:'',
  position_id:'',
  content:'',
  sort:0,
})
let formLabelAlign = reactive({
  position_id:'',
  director: '',
  check_frequency: 1,
  bugs_type: '',
  bugs_level: '',
})
const rules = reactive({
  name: [
    { required: true, message: '请填写职位名称', trigger: 'blur' },
  ]
})
const dialogRules = reactive({
  content: [
    { required: true, message: '请填写检查文本', trigger: 'blur' },
  ],
})
const tconfig = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(10, 1, 0),
})
const tconfig1 = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(10, 1, 0),
})
const tconfig2 = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(10, 1, 0),
})
// 风险select
const getpositionList = () => {
  proxy.$api.getCommonConfig().then(res => {
    res.result.position_check.type.map(item => {
      options.push({label:item,value:item})
    })
    res.result.position_check.level.map(item => {
      levelData.push({label:item,value:item})
    })
  })
}
getpositionList()
// 重置
const onReset = () => {
  tconfig.pageBean.pageIndex = 1
  getPositionLists()
}
// 搜索
const onSuccess = () => {
  tconfig.pageBean.pageIndex = 1
  getPositionLists()
}
// 新增
const clickadd = () => {
  title.value = 0
  dialogVisible.value = true
}
// 下载风险管控模板
const exportModelData = () => {
  proxy.$api.getCommonConfig().then(async(res) => {
    if(res.code == 200){
      let response = await fetch(res.result.check_excel_url);
      let blob = await response.blob();
      let objectUrl = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.href = objectUrl;
      a.download = '风险管控模板'
      a.click()
      a.remove();
    }
  })
}
// 导出安全治理清单
const exportData = async() => {
  proxy.$api.getPositionExport(form).then(res => {
    if(res){
      const blob = new Blob([res], { type: 'application/vnd.ms-excel'});
      if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, 'test')
      } else {
          const href = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = href
          a.download = proxy.$moment().format('YYYY年MM月DD日')+' 隐患排查清单'
          a.click()
          URL.revokeObjectURL(a.href)
      }
    }
  })
}

// 添加检查项目
const addProject = () => {
  confirmFlag.value = false
  dialogVisible2.value = true
}
// 导入安全事项
const handleSuccess = (src) => {
  proxy.$api.getPositionImport({url:src}).then(res => {
    if(res.code == 200){
      proxy.$message({
        type:'success',
        message:'导入成功'
      })
      tconfig.pageBean.pageIndex = 1
      getPositionLists()
    }
    fileRef.value.clearFiles()
  })
}
// 表格-安全清单
const handleSubmit = (a, b, id) => {
  title.value = 3
  dialogForm.position_id = b.id
  getPositionCheck(b.id)
  dialogVisible.value = true
}
// 表格-编辑
const handleEdit = (a, b, id) => {
  title.value = 1
  proxy.$api.getPositionCheck({position_id:b.id}).then(res => {
    for(let key in formModel) {
      formModel[key] = b[key]??1
    }
    formModel.check_frequency = res.result.position.check_frequency
  })
  dialogVisible.value = true
}
// 表格-删除
const handleDel = (a, b, id) => {
  ElMessageBox.confirm(
    '此操作将永久删除该数据,是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxy.$api.getPositionDelete({id:b.id}).then(res => {
        if(res.code == 200){
          proxy.$message({
            type: 'success',
            message: res.msg,
          })
          getPositionLists()
        }
      })
    })
    .catch(() => {
      proxy.$message({
        type: 'info',
        message: '已取消删除',
      })
    })
}
// 取消
const clickCancel = () => {
  if(title.value !== 3){
    formreset(formModel)
  }
  dialogVisible.value = false
}
// 保存
const clickComfig = () => {
  if(title.value !== 3){
    ruleFormRef.value.validate().then(flag => {
     if(flag){
       if(title.value==0){
         // 新增
         proxy.$api.getPositionCreate(formModel).then(res => {
           if(res.code == 200){
             proxy.$message({
               type:'success',
               message:res.msg
             })
             getPositionLists()
             ruleFormRef.value.concel()
             dialogVisible.value = false
           }
         })
        }else {
          // 编辑
         proxy.$api.getPositionUpdate(formModel).then(res => {
           if(res.code == 200){
             proxy.$message({
               type:'success',
               message:res.msg
             })
             getPositionLists()
             ruleFormRef.value.concel()
             dialogVisible.value = false
           }
         })
       }
     }
   })
  }else{
    proxy.$api.getPositionsave(formLabelAlign).then(res => {
      if(res.code == 200){
        proxy.$message({
          type:'success',
          message:res.msg
        })
        getPositionLists()
      }
      dialogVisible.value = false
    })
  }
}
// 分页
const pageChange = () => {
  getPositionLists()
}
// 分页
const pageChange1 = () => {}

const handleEdit1 = (a,b,id) => {
  confirmFlag.value = true
  for(let key in dialogForm){
    dialogForm[key] = b[key]
  }
  dialogForm.position_id = b.company_position_id
  dialogVisible2.value = true
}
const handleDel1 = (a,b,id) => {
  ElMessageBox.confirm(
    '此操作将永久删除该数据,是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxy.$api.getPositionCheckdel({id:b.id}).then(res => {
        if(res.code == 200){
          proxy.$message({
            type: 'success',
            message: res.msg,
          })
          getPositionCheck(dialogForm.position_id)
        }
      })
    })
    .catch(() => {
      proxy.$message({
        type: 'info',
        message: '已取消删除',
      })
    })
}
// 提交
const clickConfirm2 = async(formEl) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if(confirmFlag.value){
        proxy.$api.getPositionCheckedit(dialogForm).then(res => {
          if(res.code == 200){
            proxy.$message({
              type:'success',
              message:res.msg
            })
            getPositionCheck(dialogForm.position_id)
            dialogVisible2.value = false
          }
        })
      }else{
        proxy.$api.getPositionadd(dialogForm).then(res => {
          if(res.code == 200){
            proxy.$message({
              type:'success',
              message:res.msg
            })
            getPositionCheck(dialogForm.position_id)
            dialogVisible2.value = false
          }
        })
      }

      dialogFormRef.value.resetFields()
    }
  })
}
// 取消
const clickCancel2 = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible2.value = false
}
const beforeClose = () => {
  if(title.value !== 3){
    formreset(formModel)
  }
  activeName.value = '0'
  dialogVisible.value = false
}
const handleClose = () => {
  dialogFormRef.value.resetFields()
  dialogVisible2.value = false
}
// 岗位列表
const getPositionLists = () => {
  tconfig.tableConfig.loading = true
  form.page = tconfig.pageBean.pageIndex
  proxy.$api.getPositionLists(form).then(res => {
    tconfig.pageBean.Total = res.result.total_rows
    tconfig.tableData = res.result.lists
    tconfig.tableConfig.loading = false
  }).catch(err => tconfig.tableConfig.loading = false)
}
getPositionLists()

// 获取安全清单
const getPositionCheck = (id) => {
  proxy.$api.getPositionCheck({position_id:id}).then(res => {
    if(res.code == 200){
      positionInfo.value = res.result
      for(let key in formLabelAlign){
        formLabelAlign[key] = positionInfo.value.position[key]
      }
      formLabelAlign.position_id = id
      tconfig1.tableData = positionInfo.value.checks
    }
  }).catch(err => {ruleFormRef1.value.resetFields()})
}

// 表格-所属员工
const handleInfo = (a, b, id) => {
  dialogVisible3.value = true
  params.value.id = b.id
  getPositionMember()
  // store.commit('getActiveMenu', '1-0-2')
  // router.push({path:'/staffGroup'})
}
// 员工分页
const pageChange2 = () => {

}
const addstaff = () => {
  select_type.value = '2'
  drawerFlag.value = true
}
// 员工删除
const handleClickdel = (a, b, id) => {
  ElMessageBox.confirm(
    '此操作将永久删除该数据,是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxy.$api.getPositionMemberdel({position_id:params.value.id,staff_id:b.id}).then(res => {
        if(res.code == 200){
          proxy.$message({
            type: 'success',
            message: res.msg,
          })
          getPositionMember()
        }
      })
    })
    .catch(() => {
      proxy.$message({
        type: 'info',
        message: '已取消删除',
      })
    })
}
// 员工列表
const getPositionMember = () => {
  tconfig2.tableConfig.loading = true
  proxy.$api.getPositionMember(params.value).then(res => {
    tconfig2.tableData = res.result
    tconfig2.tableConfig.loading = false
  }).catch(err => { tconfig2.tableConfig.loading = false })
}
const drawerClose = (val) => {
  drawerFlag.value = val
}
// 添加成员
const confirmClick = (val) => {
  let data = [] as Array<string|number>
  val.map(item => {
    data.push(item.id)
  })
  proxy.$api.getPositionMemberadd({position_id:params.value.id,staff_id:data}).then(res => {
    if(res.code == 200){
        proxy.$message({
          type: 'success',
          message: res.msg,
        })
        getPositionMember()
      }
  })
}
// 初始化表格
const initTable = () => {
  tconfig.tableConfig = {
    loading: false,
    hasSelect: false,
    hasIndex: true,
    hasOperation: true,
    hasSearch: true,
    hasPage: true,
    headerShowBtn:true,
    tr: [
      {
        label: "岗位名称",
        prop: "name",
      },
      {
        label: "是否核销外来访客",
        prop: "is_doorkeeper",
        show:'template'
      },
      {
        label: "是否接收隐患提报",
        prop: "is_reception_bug",
        show:'template'
      },
      {
        label: "是否危险作业",
        prop: "is_danger",
        show:'template'
      },
      {
        label: "是否安全检查",
        prop: "is_check_bug",
        show:'template'
      },
      {
        label: "是否参加晨会答题",
        prop: "is_answer",
        show:'template'
      }
    ],
    operation:{
      label:'操作',
      width:'380',
      data:[
        { label:'所属员工', type:'', Fun:'handleInfo', id: 0 },
        { label:'排查清单', type:'', Fun:'handleSubmit', id: 1 },
        { label:'编辑', type:'', Fun:'handleEdit', id: 2 },
        { label:'删除', type:'danger', Fun:'handleDel', id: 3 },
      ]
    }
  }
}
const initTable1 = () => {
  tconfig1.tableConfig = {
    loading: false,
    hasSelect: false,
    hasIndex: false,
    hasOperation: true,
    hasSearch: true,
    hasPage: false,
    headerShowBtn:false,
    tr: [
      {
        label: "排序",
        prop: "sort",
        width:'80',
      },
      {
        label: "检查文本",
        prop: "content",
      }
    ],
    operation:{
      label:'操作',
      width:'180',
      data:[
        { label:'编辑', type:'', Fun:'handleEdit', id: 2 },
        { label:'删除', type:'danger', Fun:'handleDel', id: 3 },
      ]
    }
  }
}
const initTable2 = () => {
  tconfig2.tableConfig = {
    loading: true,
    hasSelect: false,
    hasIndex: false,
    hasOperation: true,
    hasSearch: true,
    hasPage: false,
    headerShowBtn:false,
    tr: [
      {
        label: "姓名",
        prop: "name",
      }
    ],
    operation:{
      label:'操作',
      width:'150',
      data:[
        { label:'删除', type:'danger', Fun:'handleDel', id: 1 },
      ]
    }
  }
}
initTable()
initTable1()
initTable2()
// 重置
const formreset = (form) => {
  for(let key in form){
    if(typeof(form[key])=='string'){
      form[key] = ''
    }
    if(typeof(form[key])=='number'){
      form[key] = 1
    }
    if(Array.isArray(form[key])){
      form[key] = []
    }
  }
}
</script>

<style lang='scss' scoped>
:deep(.el-dialog__body){
.el-form>.el-form-item{
  width: 70%;
  // margin-bottom: 20px;
  margin-left: 10px;
}
.el-select{
  width: 100%;
}
}
.dialog-footer{
  width: 100%;
  display: flex;
  justify-content: center;
  .el-button{
    width: 20%;
  }
}
</style>
